package com.easy.web.controller.common;

import com.easy.common.core.R;
import com.easy.common.core.domain.entity.User;
import com.easy.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.easy.common.constant.ResultConstant.*;

/**
 * 用户 配置类 控制器
 *
 * @author RuoYu
 * @date 2022/11/24
 */
@RestController
@RequestMapping("/profile")
@Api(tags = "用户配置类相关接口")
public class UserProfileController {

    @Autowired
    private UserService userService;


    /**
     * 更新用户密码
     *
     * @param userName    用户名
     * @param password    旧密码
     * @param nowPassword 新密码
     * @return {@link R}
     */
    @PutMapping("/password/edit")
    @ApiOperation(value = "更新用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "password", value = "旧密码", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "nowPassword", value = "新密码", dataTypeClass = String.class, required = true)
    })
    public R updateUserPassword(String userName, String password, String nowPassword) {

        if (userName.length() == 0 || userName == null) {
            return R.error(USERNAME_NO_NULL);
        } else if (password.length() == 0 || password == null) {
            return R.error(PLEASE_INPUT_PASSWORD);
        } else if (nowPassword.length() == 0 || nowPassword == null) {
            return R.error(PLEASE_INPUT_NOW_PASSWORD);
        }

        boolean flag = userService.checkUserPassword(userName, password);
        // 旧密码正确
        if (flag) {
            if (password.equals(nowPassword)) {
                return R.error("新密码不能和旧密码一致");
            }
            int i = userService.updateUserPasswordByUserName(userName, nowPassword);
            if (i == 1) {
                return R.success();
            }
        }

        return R.error();
    }

    /**
     * 用户信息
     *
     * @return {@link R}
     */
    @GetMapping("/account/info")
    @ApiOperation(value = "用户信息")
    @ApiImplicitParam(name = "account", value = "用户名", dataTypeClass = String.class, required = true)
    public R<User> userInfo(String account) {
        long id = Thread.currentThread().getId();
        System.out.println(id + "用户信息==================");
        User user = userService.selectUserByUserName(account);
        return R.success(user);
    }
}
